package com.csdj.server.conflg;

import com.csdj.server.pojo.Menu;
import com.csdj.server.pojo.Role;
import com.csdj.server.service.IAdminService;
import com.csdj.server.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * @Author xyx
 * @Date 2022/12/23 10:47
 * @ClassName: CustomFilter
 * @Description: 用户过滤器 根据当前的url地址 过滤 出角色列表
 * @Version 1.0
 */
@Component
public class CustomFilter implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private IMenuService menuService;
    //地址匹配实例
    AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Collection<ConfigAttribute> getAttributes(Object obj) throws IllegalArgumentException {
        //获取当前请求地址
        String requestUrl = ((FilterInvocation) obj).getRequestUrl();
        //获取菜单地址
        List<Menu> allMenuWithRole = menuService.getAllMenuWithRole();
        //循环遍历 allMenuWithRole 菜单地址
        for (Menu menu : allMenuWithRole) {
            //判断当前请求地址 跟菜单地址是否匹配
            if(antPathMatcher.match(menu.getUrl(),requestUrl)){
                //如果匹配成功 则获取
                //获取角色列表集合 menu.getRoles().stream() (stream遍历menu.getRoles())
                String[] role = menu.getRoles().stream()
                        .map(Role::getName).toArray(String[]::new);
                return SecurityConfig.createList(role);
            }
        }
        //只要登录了 这个地址 就能访问
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
